package com.shgbit.tdd.marsrover;

import lombok.Data;
import lombok.EqualsAndHashCode;


/**
 * @author liuyong
 * @date 2020/4/12 14:52
 */

@Data
@EqualsAndHashCode(exclude = "angle")
public class Position {
    private int x;
    private int y;
    private TowardEnum towardEnum;
    private int angle;

    public Position(int x, int y, TowardEnum towardEnum) {
        this.x = x;
        this.y = y;
        this.towardEnum = towardEnum;
    }

    public void forward(Mars mars) {
        x += Math.cos(Math.toRadians(angle));
        y += Math.sin(Math.toRadians(angle));
        judgeRange(mars);
    }

    public void back(Mars mars) {
        x -= Math.cos(Math.toRadians(angle));
        y -= Math.sin(Math.toRadians(angle));
        judgeRange(mars);
    }

    public void trunLeft() {
        angle += 90;
        angle = angle >= 360 ? angle - 360 : angle;
        changeToward();
    }

    public void trunRight() {
        angle -= 90;
        angle = angle < 0 ? angle + 360 : angle;
        changeToward();
    }

    private void judgeRange(Mars mars) {
        x = Math.min(Math.max(0, x), mars.getLength());
        y = Math.min(Math.max(0, y), mars.getWidth());
    }

    private void changeToward() {
        for (TowardEnum value : TowardEnum.values()) {
            if (value.getAngle() == angle) {
                this.towardEnum = value;
                break;
            }
        }
    }
}
